//
//  KyFlowWatherLayout.swift
//  KyTV
//
//  Created by fangyukui on 2017/10/26.
//  Copyright © 2017年 fangyukui. All rights reserved.
//

import UIKit
@objc protocol KyWaterfallLayoutDataSource {
    func waterfallLayout(layout:KyWaterfallLayout,hightForItem indexPath:IndexPath) -> CGFloat
    @objc optional func numberOfColsInWaterfallLayout(layout:KyWaterfallLayout) -> Int
    
}

class KyWaterfallLayout: UICollectionViewFlowLayout {
    
     // MARK: 对外提供属性
    weak var dataSource : KyWaterfallLayoutDataSource?
    
    // MARK: 私有属性
    fileprivate lazy var attrsArray  = [UICollectionViewLayoutAttributes]()
    fileprivate lazy var colHeights : [CGFloat] = {
        var colHeights = Array(repeating: self.sectionInset.top, count: self.dataSource?.numberOfColsInWaterfallLayout?(layout: self) ?? 2)
        return colHeights
    }()
    override func prepare() {
        super.prepare()
        
        // 0.获取item的个数
        let itemCount = collectionView?.numberOfItems(inSection: 0) ?? 0
        
        // 1.获取列数
        let col = dataSource?.numberOfColsInWaterfallLayout?(layout: self) ?? 2
        
        // 2.计算Item的宽度
        let itemW = (collectionView!.bounds.width - sectionInset.left - sectionInset.right -  minimumInteritemSpacing * CGFloat(col - 1))/CGFloat(col)
        
        
        // 3.计算所有的item的属性
        for  i in 0 ..< itemCount  {
            
            // 1.设置每一个Item位置相关的属性
            let indexPath = IndexPath(item: i, section: 0)
            
            let attr =  UICollectionViewLayoutAttributes(forCellWith: indexPath)
            
            // 4.取出最小列的位置
            let minH = colHeights.min()!
            let index = colHeights.index(of: minH)!
            
            let width = itemW

            let height = dataSource?.waterfallLayout(layout: self, hightForItem: indexPath) ?? 0
            
            let x = sectionInset.left + (minimumInteritemSpacing + itemW) * CGFloat(index)
            let y = minH + minimumLineSpacing
            
            attr.frame = CGRect(x: x, y: y, width: width, height: height)
            
            colHeights[index] = (y + height)
            
            
            attrsArray.append(attr)
            
            
        }
        
    }

}


extension KyWaterfallLayout{
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrsArray
    }
    override var collectionViewContentSize: CGSize{
        
        return CGSize(width: collectionView!.bounds.width, height: colHeights.max()! + sectionInset.bottom)
    }
}
